package com.effectiv.gooruda.rest.api.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.stereotype.Component;

import com.effectiv.gooruda.rest.api.operation.DataStorageOperations;
import com.effectiv.gooruda.security.rest.RESTSecurityUtil;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;

@Slf4j
@Component
public class DataStorageServiceImpl implements DataStorageOperations{
	
	@Autowired
	private MongoTemplate template;
	
	private String COLLECTION_NAME_TEMPLATE = "cst_coll_";
	
	@Override
	public String save(String collection, String data) {
		DBObject dbObject = (DBObject) JSON.parse(data);
		//dbObject.put("_id", null);
		
		String collName = COLLECTION_NAME_TEMPLATE + collection + "_" + RESTSecurityUtil.getAppId();
		
		template.getCollection(collName).insert(dbObject);
		
		
		return JSON.serialize(dbObject);
	}

	@Override
	public List<String> findAll(String collection, String query) {
		
		log.debug("Query = {}", query);
		
		BasicQuery q = new BasicQuery(query);
		
		String collectionName = COLLECTION_NAME_TEMPLATE + collection + "_" + RESTSecurityUtil.getAppId();
		
		List data = template.find(q, Map.class, collectionName);
		List<String> dataList = null;
		if(data != null){
			
			dataList = new ArrayList<String>();
			
			for(Object o : data){
				dataList.add(JSON.serialize(data));
			}
		}
		
		return dataList;		
		
	}
	
}
